﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Threading;
using System.ServiceModel;
using System.IO;
using LINQAmazonProvider;  
using Common;
using System.Text;
//using SerchEngine;



namespace LINQAmazonProvider
{
    public class AmazonSearch
    {
        private static List<string> ListResult;

        public static ManualResetEvent alldone;

        public static bool firstResult = true;
        public static int startPage = 1;
        public static int finalPage = 10;
        

        // Performs the REST search
        public List<string> PerformWebServiceSearch(Dictionary<string, string> parameters)
        {
            Double ItemsPerPage = 10;
            ListResult = new List<string>();

            if (parameters.ContainsKey("Skip"))
            {
                startPage += Convert.ToInt32(int.Parse(parameters["Skip"]) / ItemsPerPage);
                parameters.Remove("Skip");
            }
            if (parameters.ContainsKey("Take"))
            {
                finalPage = startPage + Convert.ToInt32(Math.Ceiling((Double.Parse((parameters["Take"])) - 1) / ItemsPerPage)) - 1;
            }

            // Set the iterator
            int iteratorValue = startPage;

            // Build the REST request
            StringBuilder baseURL = new StringBuilder("http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&Operation=ItemSearch&AWSAccessKeyId=0TD9TEYEE3NDY01M6D02&SearchIndex=Books&ResponseGroup=Medium");
            
            foreach (KeyValuePair<string, string> item in parameters)
            {
                if (!item.Key.Equals("Method") && !item.Key.Equals("Take") && !item.Value.Equals("") && !item.Value.Equals("0"))
                {
                    if (item.Key.Equals("Category"))
                    {
                        baseURL.Append("&").Append("BrowseNode").Append("=").Append(item.Value);
                    }
                    else
                    {
                        baseURL.Append("&").Append(item.Key).Append("=").Append(item.Value);
                    }
                }
            }

            baseURL = baseURL.Replace(" ", "%20");

            while (iteratorValue <= finalPage)
            {
                alldone = new ManualResetEvent(false);
                //StringBuilder baseUrlAux = new StringBuilder(baseURL.ToString());
                RestDataAccess da = new RestDataAccess(baseURL.ToString() + "&ItemPage=" + iteratorValue);
                da.RestRequestCompleted += new RestDataAccess.RestRequestCompletedHandler(da_RestRequestCompleted);
                da.PerformRestRequest();
                alldone.WaitOne();
                
                iteratorValue++;
            }
            alldone.Close();
                                   
            return ListResult;
        }

        static void da_RestRequestCompleted(object sender, RestRequestCompletedEventArgs e)
        {
            //Posible proceso del response
            if (firstResult)
            {
                int totalPages = ResultXMLParser.GetTotalPagesQueryResult(e.Result);
                if (totalPages < finalPage)
                {
                    finalPage = totalPages;
                }
                if (totalPages >= startPage) {
                    ListResult.Add(e.Result);
                }
                firstResult = false;
            }
            else {
                ListResult.Add(e.Result);
            }

            alldone.Set();
        }
    }
}
